import { store } from "../index.js";
import { defineStore } from "pinia";
import { getShiftTime } from "../../utils/datetime";
import { useInfoStoreHook } from "./info";
import { useProcessStoreHook } from "./process";
import { ElMessage, ElMessageBox } from "element-plus";

export const useDetectionStore = defineStore("detection", {
  state: () => ({
    // 过程点检数据集
    dataset: [],
    // 送检数据集
    inspects: [],
    // 所有测量字段
    fields: [],
    // 未登录提示是否存在
    tipsVisible: false
  }),
  getters: {
    fieldItems() {
      const result = [];
      this.fields?.forEach((v) => {
        if (v.method !== 3) {
          result.push({
            text: v.name,
            method: v.method
          });
        }
      });
      return result;
    },
    measureFields() {
      const result = [];
      this.fields?.forEach((v) => {
        if (v.method === 0) result.push(v);
      });
      return result;
    },
    inspectFields() {
      const result = [];
      this.fields?.forEach((v) => {
        if (v.method === 3 || v.method === 4) result.push(v);
      });
      return result;
    },
    otherFields() {
      const result = [];
      this.fields?.forEach((v) => {
        if (v.method === 1) v.value = 1;
        if (v.method === 1 || v.method === 2) result.push(v);
      });
      return result;
    }
  },
  actions: {
    setFields(newFields) {
      this.fields = newFields;
    },
    async updateDataset() {
      const dataset = [];
      const inspects = {};
      const userInfo = useInfoStoreHook();
      // 初始化送检项目表头
      const processStore = useProcessStoreHook();
      this.inspectFields.forEach((f) => {
        const param = processStore.technicParams[f.name];
        let nameWithRange = f.name;
        if (param) {
          nameWithRange = `${nameWithRange}\n（${param.min} ~ ${param.max}）`;
        }
        inspects[f.name] = { name: nameWithRange, 3: [], 4: [] };
      });
      const timeRange = getShiftTime();
      const spcData = await window.api.spcGetTarget(
        processStore.processSrc,
        timeRange[0],
        timeRange[1]
      );
      spcData.forEach((d) => {
        // 0-过程点检 1-量仪点检 2-全检 3-首件送检 4-过程送检 5-20件全检 6-小批全检
        if (d.work_type === 3 || d.work_type === 4) {
          d.data.forEach((i) => {
            if (!inspects[i.type]) return;
            inspects[i.type][d.work_type].push({
              uuid: d.uuid,
              reported: d.reported,
              value: i.value
            });
          });
        } else {
          dataset.push(d);
        }
      });
      const inspectArr = [];
      for (const key in inspects) {
        inspectArr.push(inspects[key]);
      }
      this.inspects = inspectArr;
      this.dataset = dataset;
    },
    async insertData(qrCode, workType = undefined) {
      /**
       * qrcode: 零件二维码
       * workType: 作业类型，分为：0-过程点检 1-量仪点检 2-全检 3-首件送检 4-过程送检
       * 10开始为20件全检的细类：10-切换型号 11-停机恢复 12-调机确认 13-砂轮刀具更换
       */
      const info = useInfoStoreHook();
      const processStore = useProcessStoreHook();
      if (this.tipsVisible) return;
      if (!info.isLogin) {
        this.tipsVisible = true;
        await ElMessageBox.alert("请先登录再进行操作！", "未登录", {
          type: "error",
          confirmButtonText: "OK",
          customClass: "el-err-msg",
          appendTo: "body"
        }).then(() => {
          this.tipsVisible = false;
        });
        return;
      }
      if (!processStore.processSrc) {
        await ElMessageBox.alert("请先选择作业岗位再进行操作！", "未选择岗位", {
          type: "error",
          confirmButtonText: "OK",
          customClass: "el-err-msg",
          appendTo: "body"
        }).then(() => {
          this.tipsVisible = false;
        });
        return;
      }
      if (!processStore.modelCode) {
        await ElMessageBox.alert("请先选择生产型号再进行操作！", "未选择生产型号", {
          type: "error",
          confirmButtonText: "OK",
          customClass: "el-err-msg",
          appendTo: "body"
        }).then(() => {
          this.tipsVisible = false;
        });
        return;
      }
      const data = {
        uuid: qrCode,
        process: processStore.processSrc,
        model: processStore.modelCode,
        part_type: processStore.workCenterType,
        work_type: workType ?? info.work_type,
        line_id: processStore.workCenterId,
        operator: info.username,
        operator_name: info.realname,
        identity: info.identity,
        reported: 0,
        create_at: +new Date(),
        data: []
      };
      let dataCompleteFlag = true;
      // 将数据转换为数据库存储的标准格式
      this.fields?.forEach((f) => {
        // 未选择作业类型时默认为过程点检，测量手段是送检的字段跳过
        if (!workType && f.method === 3) return;
        // workType为3,4时为送检数据提交，此时跳过非送检类型数据
        if (workType && (workType === 3 || workType === 4) && f.method !== 3) return;
        let qualified = f.value;
        if (f.method !== 1) {
          qualified = 1;
          // if (typeof f.value !== 'number' && !f.value) dataCompleteFlag = false
        }
        // 数值型数据为空时判断为未检测字段，自动跳过
        if (typeof f.value !== "number" && !f.value) {
          return;
        }
        data.data.push({
          type: f.name,
          value: f.value,
          qualified: qualified
        });
      });
      if (!dataCompleteFlag) {
        ElMessage.error("零件数据不完整！请完成零件测量后再进行提报！");
        return;
      }
      const res = await window.api.insertData(data);
      if (res) {
        await this.updateDataset();
        await this.clearData();
        ElMessage.success(`零件(${data.uuid})数据插入成功！`);
      } else {
        ElMessage.error(`零件(${data.uuid})数据插入失败！`);
      }
    },
    // 将上一次测量保留的字段数据清空
    async clearData() {
      if (this.fields) {
        for (let i = 0; i < this.fields.length; i++) {
          if (this.fields[i].method !== 1) this.fields[i].value = null;
        }
      }
    },
    // 结束同一批次的数据记录，将此次记录的所有数据的finish标识置为结束的时间戳
    async finishBatch() {
      await window.api.finishBatch();
    }
  }
});

export function useDetectionStoreHook() {
  return useDetectionStore(store);
}
